

<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
  <meta charset="utf-8">
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="Description" content="scikit-learn: machine learning in Python">

  
  <title>Supervised learning: predicting an output variable from high-dimensional observations &mdash; scikit-learn 0.22 documentation</title>
  
  <link rel="canonical" href="http://scikit-learn.org/stable/tutorial/statistical_inference/supervised_learning.html" />

  
  <link rel="shortcut icon" href="../../_static/favicon.ico"/>
  

  <link rel="stylesheet" href="../../_static/css/vendor/bootstrap.min.css" type="text/css" />
  <link rel="stylesheet" href="../../_static/gallery.css" type="text/css" />
  <link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" />
<script id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
<script src="../../_static/jquery.js"></script> 
</head>
<body>
<nav id="navbar" class="sk-docs-navbar navbar navbar-expand-md navbar-light bg-light py-0">
  <div class="container-fluid sk-docs-container px-0">
      <a class="navbar-brand py-0" href="../../index.html">
        <img
          class="sk-brand-img"
          src="../../_static/scikit-learn-logo-small.png"
          alt="logo"/>
      </a>
    <button
      id="sk-navbar-toggler"
      class="navbar-toggler"
      type="button"
      data-toggle="collapse"
      data-target="#navbarSupportedContent"
      aria-controls="navbarSupportedContent"
      aria-expanded="false"
      aria-label="Toggle navigation"
    >
      <span class="navbar-toggler-icon"></span>
    </button>

    <div class="sk-navbar-collapse collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav mr-auto">
        <li class="nav-item">
          <a class="sk-nav-link nav-link" href="../../install.html">Install</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link" href="../../user_guide.html">User Guide</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link" href="../../modules/classes.html">API</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link" href="../../auto_examples/index.html">Examples</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../../getting_started.html">Getting Started</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../index.html">Tutorial</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../../glossary.html">Glossary</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../../developers/index.html">Development</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../../faq.html">FAQ</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../../related_projects.html">Related packages</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../../roadmap.html">Roadmap</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../../about.html">About us</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link nav-more-item-mobile-items" href="https://github.com/scikit-learn/scikit-learn">GitHub</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link nav-more-item-mobile-items" href="https://scikit-learn.org/dev/versions.html">Other Versions</a>
        </li>
        <li class="nav-item dropdown nav-more-item-dropdown">
          <a class="sk-nav-link nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">More</a>
          <div class="dropdown-menu" aria-labelledby="navbarDropdown">
              <a class="sk-nav-dropdown-item dropdown-item" href="../../getting_started.html">Getting Started</a>
              <a class="sk-nav-dropdown-item dropdown-item" href="../index.html">Tutorial</a>
              <a class="sk-nav-dropdown-item dropdown-item" href="../../glossary.html">Glossary</a>
              <a class="sk-nav-dropdown-item dropdown-item" href="../../developers/index.html">Development</a>
              <a class="sk-nav-dropdown-item dropdown-item" href="../../faq.html">FAQ</a>
              <a class="sk-nav-dropdown-item dropdown-item" href="../../related_projects.html">Related packages</a>
              <a class="sk-nav-dropdown-item dropdown-item" href="../../roadmap.html">Roadmap</a>
              <a class="sk-nav-dropdown-item dropdown-item" href="../../about.html">About us</a>
              <a class="sk-nav-dropdown-item dropdown-item" href="https://github.com/scikit-learn/scikit-learn">GitHub</a>
              <a class="sk-nav-dropdown-item dropdown-item" href="https://scikit-learn.org/dev/versions.html">Other Versions</a>
          </div>
        </li>
      </ul>
      <div id="searchbox" role="search">
          <div class="searchformwrapper">
          <form class="search" action="../../search.html" method="get">
            <input class="sk-search-text-input" type="text" name="q" aria-labelledby="searchlabel" />
            <input class="sk-search-text-btn" type="submit" value="Go" />
          </form>
          </div>
      </div>
    </div>
  </div>
</nav>
<div class="d-flex" id="sk-doc-wrapper">
    <input type="checkbox" name="sk-toggle-checkbox" id="sk-toggle-checkbox">
    <label id="sk-sidemenu-toggle" class="sk-btn-toggle-toc btn sk-btn-primary" for="sk-toggle-checkbox">Toggle Menu</label>
    <div id="sk-sidebar-wrapper" class="border-right">
      <div class="sk-sidebar-toc-wrapper">
        <div class="sk-sidebar-toc-logo">
          <a href="../../index.html">
            <img
              class="sk-brand-img"
              src="../../_static/scikit-learn-logo-small.png"
              alt="logo"/>
          </a>
        </div>
        <div class="btn-group w-100 mb-2" role="group" aria-label="rellinks">
            <a href="settings.html" role="button" class="btn sk-btn-rellink py-1" sk-rellink-tooltip="Statistical learning: the setting and the estimator object in scikit-learn">Prev</a><a href="index.html" role="button" class="btn sk-btn-rellink py-1" sk-rellink-tooltip="A tutorial on statistical-learning for scientific data processing">Up</a>
            <a href="model_selection.html" role="button" class="btn sk-btn-rellink py-1" sk-rellink-tooltip="Model selection: choosing estimators and their parameters">Next</a>
        </div>
        <div class="alert alert-danger p-1 mb-2" role="alert">
          <p class="text-center mb-0">
          <strong>scikit-learn 0.22</strong><br/>
          <a href="http://scikit-learn.org/dev/versions.html">Other versions</a>
          </p>
        </div>
        <div class="alert alert-warning p-1 mb-2" role="alert">
          <p class="text-center mb-0">
            Please <a class="font-weight-bold" href="../../about.html#citing-scikit-learn"><string>cite us</string></a> if you use the software.
          </p>
        </div>
          <div class="sk-sidebar-toc">
            <ul>
<li><a class="reference internal" href="#">Supervised learning: predicting an output variable from high-dimensional observations</a><ul>
<li><a class="reference internal" href="#nearest-neighbor-and-the-curse-of-dimensionality">Nearest neighbor and the curse of dimensionality</a><ul>
<li><a class="reference internal" href="#k-nearest-neighbors-classifier">k-Nearest neighbors classifier</a></li>
<li><a class="reference internal" href="#the-curse-of-dimensionality">The curse of dimensionality</a></li>
</ul>
</li>
<li><a class="reference internal" href="#linear-model-from-regression-to-sparsity">Linear model: from regression to sparsity</a><ul>
<li><a class="reference internal" href="#linear-regression">Linear regression</a></li>
<li><a class="reference internal" href="#shrinkage">Shrinkage</a></li>
<li><a class="reference internal" href="#sparsity">Sparsity</a></li>
<li><a class="reference internal" href="#classification">Classification</a></li>
</ul>
</li>
<li><a class="reference internal" href="#support-vector-machines-svms">Support vector machines (SVMs)</a><ul>
<li><a class="reference internal" href="#linear-svms">Linear SVMs</a></li>
<li><a class="reference internal" href="#using-kernels">Using kernels</a></li>
</ul>
</li>
</ul>
</li>
</ul>

          </div>
      </div>
    </div>
    <div id="sk-page-content-wrapper">
      <div class="sk-page-content container-fluid body px-md-3" role="main">
        
  <div class="section" id="supervised-learning-predicting-an-output-variable-from-high-dimensional-observations">
<span id="supervised-learning-tut"></span><h1>Supervised learning: predicting an output variable from high-dimensional observations<a class="headerlink" href="#supervised-learning-predicting-an-output-variable-from-high-dimensional-observations" title="Permalink to this headline">¶</a></h1>
<div class="topic">
<p class="topic-title">The problem solved in supervised learning</p>
<p><a class="reference internal" href="../../supervised_learning.html#supervised-learning"><span class="std std-ref">Supervised learning</span></a>
consists in learning the link between two
datasets: the observed data <code class="docutils literal notranslate"><span class="pre">X</span></code> and an external variable <code class="docutils literal notranslate"><span class="pre">y</span></code> that we
are trying to predict, usually called “target” or “labels”. Most often,
<code class="docutils literal notranslate"><span class="pre">y</span></code> is a 1D array of length <code class="docutils literal notranslate"><span class="pre">n_samples</span></code>.</p>
<p>All supervised <a class="reference external" href="https://en.wikipedia.org/wiki/Estimator">estimators</a>
in scikit-learn implement a <code class="docutils literal notranslate"><span class="pre">fit(X,</span> <span class="pre">y)</span></code> method to fit the model
and a <code class="docutils literal notranslate"><span class="pre">predict(X)</span></code> method that, given unlabeled observations <code class="docutils literal notranslate"><span class="pre">X</span></code>,
returns the predicted labels <code class="docutils literal notranslate"><span class="pre">y</span></code>.</p>
</div>
<div class="topic">
<p class="topic-title">Vocabulary: classification and regression</p>
<p>If the prediction task is to classify the observations in a set of
finite labels, in other words to “name” the objects observed, the task
is said to be a <strong>classification</strong> task. On the other hand, if the goal
is to predict a continuous target variable, it is said to be a
<strong>regression</strong> task.</p>
<p>When doing classification in scikit-learn, <code class="docutils literal notranslate"><span class="pre">y</span></code> is a vector of integers
or strings.</p>
<p>Note: See the <a class="reference internal" href="../basic/tutorial.html#introduction"><span class="std std-ref">Introduction to machine learning with scikit-learn
Tutorial</span></a> for a quick run-through on the basic machine
learning vocabulary used within scikit-learn.</p>
</div>
<div class="section" id="nearest-neighbor-and-the-curse-of-dimensionality">
<h2>Nearest neighbor and the curse of dimensionality<a class="headerlink" href="#nearest-neighbor-and-the-curse-of-dimensionality" title="Permalink to this headline">¶</a></h2>
<div class="topic">
<p class="topic-title">Classifying irises:</p>
<a class="reference external image-reference" href="../../auto_examples/datasets/plot_iris_dataset.html"><img alt="auto_examples/datasets/images/sphx_glr_plot_iris_dataset_001.png" class="align-right" src="auto_examples/datasets/images/sphx_glr_plot_iris_dataset_001.png" /></a>
<p>The iris dataset is a classification task consisting in identifying 3
different types of irises (Setosa, Versicolour, and Virginica) from
their petal and sepal length and width:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">sklearn</span> <span class="kn">import</span> <span class="n">datasets</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">iris_X</span><span class="p">,</span> <span class="n">iris_y</span> <span class="o">=</span> <span class="n">datasets</span><span class="o">.</span><span class="n">load_iris</span><span class="p">(</span><span class="n">return_X_y</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">np</span><span class="o">.</span><span class="n">unique</span><span class="p">(</span><span class="n">iris_y</span><span class="p">)</span>
<span class="go">array([0, 1, 2])</span>
</pre></div>
</div>
</div>
<div class="section" id="k-nearest-neighbors-classifier">
<h3>k-Nearest neighbors classifier<a class="headerlink" href="#k-nearest-neighbors-classifier" title="Permalink to this headline">¶</a></h3>
<p>The simplest possible classifier is the
<a class="reference external" href="https://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm">nearest neighbor</a>:
given a new observation <code class="docutils literal notranslate"><span class="pre">X_test</span></code>, find in the training set (i.e. the data
used to train the estimator) the observation with the closest feature vector.
(Please see the <a class="reference internal" href="../../modules/neighbors.html#neighbors"><span class="std std-ref">Nearest Neighbors section</span></a> of the online
Scikit-learn documentation for more information about this type of classifier.)</p>
<div class="topic">
<p class="topic-title">Training set and testing set</p>
<p>While experimenting with any learning algorithm, it is important not to
test the prediction of an estimator on the data used to fit the
estimator as this would not be evaluating the performance of the
estimator on <strong>new data</strong>. This is why datasets are often split into
<em>train</em> and <em>test</em> data.</p>
</div>
<p><strong>KNN (k nearest neighbors) classification example</strong>:</p>
<a class="reference external image-reference" href="../../auto_examples/neighbors/plot_classification.html"><img alt="auto_examples/neighbors/images/sphx_glr_plot_classification_001.png" class="align-center" src="auto_examples/neighbors/images/sphx_glr_plot_classification_001.png" /></a>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Split iris data in train and test data</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># A random permutation, to split the data randomly</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">seed</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">indices</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">permutation</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">iris_X</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">iris_X_train</span> <span class="o">=</span> <span class="n">iris_X</span><span class="p">[</span><span class="n">indices</span><span class="p">[:</span><span class="o">-</span><span class="mi">10</span><span class="p">]]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">iris_y_train</span> <span class="o">=</span> <span class="n">iris_y</span><span class="p">[</span><span class="n">indices</span><span class="p">[:</span><span class="o">-</span><span class="mi">10</span><span class="p">]]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">iris_X_test</span> <span class="o">=</span> <span class="n">iris_X</span><span class="p">[</span><span class="n">indices</span><span class="p">[</span><span class="o">-</span><span class="mi">10</span><span class="p">:]]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">iris_y_test</span> <span class="o">=</span> <span class="n">iris_y</span><span class="p">[</span><span class="n">indices</span><span class="p">[</span><span class="o">-</span><span class="mi">10</span><span class="p">:]]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Create and fit a nearest-neighbor classifier</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">sklearn.neighbors</span> <span class="kn">import</span> <span class="n">KNeighborsClassifier</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">knn</span> <span class="o">=</span> <span class="n">KNeighborsClassifier</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">knn</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">iris_X_train</span><span class="p">,</span> <span class="n">iris_y_train</span><span class="p">)</span>
<span class="go">KNeighborsClassifier()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">knn</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">iris_X_test</span><span class="p">)</span>
<span class="go">array([1, 2, 1, 0, 0, 0, 2, 1, 2, 0])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">iris_y_test</span>
<span class="go">array([1, 1, 1, 0, 0, 0, 2, 1, 2, 0])</span>
</pre></div>
</div>
</div>
<div class="section" id="the-curse-of-dimensionality">
<span id="curse-of-dimensionality"></span><h3>The curse of dimensionality<a class="headerlink" href="#the-curse-of-dimensionality" title="Permalink to this headline">¶</a></h3>
<p>For an estimator to be effective, you need the distance between neighboring
points to be less than some value <span class="math notranslate nohighlight">\(d\)</span>, which depends on the problem.
In one dimension, this requires on average <span class="math notranslate nohighlight">\(n \sim 1/d\)</span> points.
In the context of the above <span class="math notranslate nohighlight">\(k\)</span>-NN example, if the data is described by
just one feature with values ranging from 0 to 1 and with <span class="math notranslate nohighlight">\(n\)</span> training
observations, then new data will be no further away than <span class="math notranslate nohighlight">\(1/n\)</span>.
Therefore, the nearest neighbor decision rule will be efficient as soon as
<span class="math notranslate nohighlight">\(1/n\)</span> is small compared to the scale of between-class feature variations.</p>
<p>If the number of features is <span class="math notranslate nohighlight">\(p\)</span>, you now require <span class="math notranslate nohighlight">\(n \sim 1/d^p\)</span>
points.  Let’s say that we require 10 points in one dimension: now <span class="math notranslate nohighlight">\(10^p\)</span>
points are required in <span class="math notranslate nohighlight">\(p\)</span> dimensions to pave the <span class="math notranslate nohighlight">\([0, 1]\)</span> space.
As <span class="math notranslate nohighlight">\(p\)</span> becomes large, the number of training points required for a good
estimator grows exponentially.</p>
<p>For example, if each point is just a single number (8 bytes), then an
effective <span class="math notranslate nohighlight">\(k\)</span>-NN estimator in a paltry <span class="math notranslate nohighlight">\(p \sim 20\)</span> dimensions would
require more training data than the current estimated size of the entire
internet (±1000 Exabytes or so).</p>
<p>This is called the
<a class="reference external" href="https://en.wikipedia.org/wiki/Curse_of_dimensionality">curse of dimensionality</a>
and is a core problem that machine learning addresses.</p>
</div>
</div>
<div class="section" id="linear-model-from-regression-to-sparsity">
<h2>Linear model: from regression to sparsity<a class="headerlink" href="#linear-model-from-regression-to-sparsity" title="Permalink to this headline">¶</a></h2>
<div class="topic">
<p class="topic-title">Diabetes dataset</p>
<p>The diabetes dataset consists of 10 physiological variables (age,
sex, weight, blood pressure) measure on 442 patients, and an
indication of disease progression after one year:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">diabetes_X</span><span class="p">,</span> <span class="n">diabetes_y</span> <span class="o">=</span> <span class="n">datasets</span><span class="o">.</span><span class="n">load_diabetes</span><span class="p">(</span><span class="n">return_X_y</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">diabetes_X_train</span> <span class="o">=</span> <span class="n">diabetes_X</span><span class="p">[:</span><span class="o">-</span><span class="mi">20</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">diabetes_X_test</span>  <span class="o">=</span> <span class="n">diabetes_X</span><span class="p">[</span><span class="o">-</span><span class="mi">20</span><span class="p">:]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">diabetes_y_train</span> <span class="o">=</span> <span class="n">diabetes_y</span><span class="p">[:</span><span class="o">-</span><span class="mi">20</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">diabetes_y_test</span>  <span class="o">=</span> <span class="n">diabetes_y</span><span class="p">[</span><span class="o">-</span><span class="mi">20</span><span class="p">:]</span>
</pre></div>
</div>
<p>The task at hand is to predict disease progression from physiological
variables.</p>
</div>
<div class="section" id="linear-regression">
<h3>Linear regression<a class="headerlink" href="#linear-regression" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="../../modules/generated/sklearn.linear_model.LinearRegression.html#sklearn.linear_model.LinearRegression" title="sklearn.linear_model.LinearRegression"><code class="xref py py-class docutils literal notranslate"><span class="pre">LinearRegression</span></code></a>,
in its simplest form, fits a linear model to the data set by adjusting
a set of parameters in order to make the sum of the squared residuals
of the model as small as possible.</p>
<a class="reference external image-reference" href="../../auto_examples/linear_model/plot_ols.html"><img alt="auto_examples/linear_model/images/sphx_glr_plot_ols_001.png" class="align-right" src="auto_examples/linear_model/images/sphx_glr_plot_ols_001.png" /></a>
<p>Linear models: <span class="math notranslate nohighlight">\(y = X\beta + \epsilon\)</span></p>
<blockquote>
<div><ul class="simple">
<li><p><span class="math notranslate nohighlight">\(X\)</span>: data</p></li>
<li><p><span class="math notranslate nohighlight">\(y\)</span>: target variable</p></li>
<li><p><span class="math notranslate nohighlight">\(\beta\)</span>: Coefficients</p></li>
<li><p><span class="math notranslate nohighlight">\(\epsilon\)</span>: Observation noise</p></li>
</ul>
</div></blockquote>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">sklearn</span> <span class="kn">import</span> <span class="n">linear_model</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">regr</span> <span class="o">=</span> <span class="n">linear_model</span><span class="o">.</span><span class="n">LinearRegression</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">regr</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">diabetes_X_train</span><span class="p">,</span> <span class="n">diabetes_y_train</span><span class="p">)</span>
<span class="go">LinearRegression()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">regr</span><span class="o">.</span><span class="n">coef_</span><span class="p">)</span>  
<span class="go">[   0.30349955 -237.63931533  510.53060544  327.73698041 -814.13170937</span>
<span class="go">  492.81458798  102.84845219  184.60648906  743.51961675   76.09517222]</span>


<span class="gp">&gt;&gt;&gt; </span><span class="c1"># The mean square error</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">np</span><span class="o">.</span><span class="n">mean</span><span class="p">((</span><span class="n">regr</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">diabetes_X_test</span><span class="p">)</span> <span class="o">-</span> <span class="n">diabetes_y_test</span><span class="p">)</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span>
<span class="go">2004.56760268...</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Explained variance score: 1 is perfect prediction</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># and 0 means that there is no linear relationship</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># between X and y.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">regr</span><span class="o">.</span><span class="n">score</span><span class="p">(</span><span class="n">diabetes_X_test</span><span class="p">,</span> <span class="n">diabetes_y_test</span><span class="p">)</span>
<span class="go">0.5850753022690...</span>
</pre></div>
</div>
</div>
<div class="section" id="shrinkage">
<span id="id2"></span><h3>Shrinkage<a class="headerlink" href="#shrinkage" title="Permalink to this headline">¶</a></h3>
<p>If there are few data points per dimension, noise in the observations
induces high variance:</p>
<a class="reference external image-reference" href="../../auto_examples/linear_model/plot_ols_ridge_variance.html"><img alt="auto_examples/linear_model/images/sphx_glr_plot_ols_ridge_variance_001.png" class="align-right" src="auto_examples/linear_model/images/sphx_glr_plot_ols_ridge_variance_001.png" /></a>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">X</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">c_</span><span class="p">[</span> <span class="o">.</span><span class="mi">5</span><span class="p">,</span> <span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">T</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="p">[</span><span class="o">.</span><span class="mi">5</span><span class="p">,</span> <span class="mi">1</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">test</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">c_</span><span class="p">[</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">2</span><span class="p">]</span><span class="o">.</span><span class="n">T</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">regr</span> <span class="o">=</span> <span class="n">linear_model</span><span class="o">.</span><span class="n">LinearRegression</span><span class="p">()</span>

<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="k">as</span> <span class="nn">plt</span> 
<span class="gp">&gt;&gt;&gt; </span><span class="n">plt</span><span class="o">.</span><span class="n">figure</span><span class="p">()</span> 

<span class="gp">&gt;&gt;&gt; </span><span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">seed</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">_</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">6</span><span class="p">):</span> 
<span class="gp">... </span>    <span class="n">this_X</span> <span class="o">=</span> <span class="o">.</span><span class="mi">1</span> <span class="o">*</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">normal</span><span class="p">(</span><span class="n">size</span><span class="o">=</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">1</span><span class="p">))</span> <span class="o">+</span> <span class="n">X</span>
<span class="gp">... </span>    <span class="n">regr</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">this_X</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
<span class="gp">... </span>    <span class="n">plt</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">test</span><span class="p">,</span> <span class="n">regr</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">test</span><span class="p">))</span> 
<span class="gp">... </span>    <span class="n">plt</span><span class="o">.</span><span class="n">scatter</span><span class="p">(</span><span class="n">this_X</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">s</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>  
</pre></div>
</div>
<p>A solution in high-dimensional statistical learning is to <em>shrink</em> the
regression coefficients to zero: any two randomly chosen set of
observations are likely to be uncorrelated. This is called <a class="reference internal" href="../../modules/generated/sklearn.linear_model.Ridge.html#sklearn.linear_model.Ridge" title="sklearn.linear_model.Ridge"><code class="xref py py-class docutils literal notranslate"><span class="pre">Ridge</span></code></a>
regression:</p>
<a class="reference external image-reference" href="../../auto_examples/linear_model/plot_ols_ridge_variance.html"><img alt="auto_examples/linear_model/images/sphx_glr_plot_ols_ridge_variance_002.png" class="align-right" src="auto_examples/linear_model/images/sphx_glr_plot_ols_ridge_variance_002.png" /></a>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">regr</span> <span class="o">=</span> <span class="n">linear_model</span><span class="o">.</span><span class="n">Ridge</span><span class="p">(</span><span class="n">alpha</span><span class="o">=.</span><span class="mi">1</span><span class="p">)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">plt</span><span class="o">.</span><span class="n">figure</span><span class="p">()</span> 

<span class="gp">&gt;&gt;&gt; </span><span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">seed</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">_</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">6</span><span class="p">):</span> 
<span class="gp">... </span>    <span class="n">this_X</span> <span class="o">=</span> <span class="o">.</span><span class="mi">1</span> <span class="o">*</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">normal</span><span class="p">(</span><span class="n">size</span><span class="o">=</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">1</span><span class="p">))</span> <span class="o">+</span> <span class="n">X</span>
<span class="gp">... </span>    <span class="n">regr</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">this_X</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
<span class="gp">... </span>    <span class="n">plt</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">test</span><span class="p">,</span> <span class="n">regr</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">test</span><span class="p">))</span> 
<span class="gp">... </span>    <span class="n">plt</span><span class="o">.</span><span class="n">scatter</span><span class="p">(</span><span class="n">this_X</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">s</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span> 
</pre></div>
</div>
<p>This is an example of <strong>bias/variance tradeoff</strong>: the larger the ridge
<code class="docutils literal notranslate"><span class="pre">alpha</span></code> parameter, the higher the bias and the lower the variance.</p>
<p>We can choose <code class="docutils literal notranslate"><span class="pre">alpha</span></code> to minimize left out error, this time using the
diabetes dataset rather than our synthetic data:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">alphas</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">logspace</span><span class="p">(</span><span class="o">-</span><span class="mi">4</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">([</span><span class="n">regr</span><span class="o">.</span><span class="n">set_params</span><span class="p">(</span><span class="n">alpha</span><span class="o">=</span><span class="n">alpha</span><span class="p">)</span>
<span class="gp">... </span>           <span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">diabetes_X_train</span><span class="p">,</span> <span class="n">diabetes_y_train</span><span class="p">)</span>
<span class="gp">... </span>           <span class="o">.</span><span class="n">score</span><span class="p">(</span><span class="n">diabetes_X_test</span><span class="p">,</span> <span class="n">diabetes_y_test</span><span class="p">)</span>
<span class="gp">... </span>       <span class="k">for</span> <span class="n">alpha</span> <span class="ow">in</span> <span class="n">alphas</span><span class="p">])</span>
<span class="go">[0.5851110683883..., 0.5852073015444..., 0.5854677540698...,</span>
<span class="go"> 0.5855512036503..., 0.5830717085554..., 0.57058999437...]</span>
</pre></div>
</div>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>Capturing in the fitted parameters noise that prevents the model to
generalize to new data is called
<a class="reference external" href="https://en.wikipedia.org/wiki/Overfitting">overfitting</a>. The bias introduced
by the ridge regression is called a
<a class="reference external" href="https://en.wikipedia.org/wiki/Regularization_%28machine_learning%29">regularization</a>.</p>
</div>
</div>
<div class="section" id="sparsity">
<span id="id3"></span><h3>Sparsity<a class="headerlink" href="#sparsity" title="Permalink to this headline">¶</a></h3>
<p class="centered"><strong>Fitting only features 1 and 2</strong></p>
<p class="centered">
<strong><a class="reference external" href="../../auto_examples/linear_model/plot_ols_3d.html"><img alt="diabetes_ols_1" src="auto_examples/linear_model/images/sphx_glr_plot_ols_3d_001.png" /></a> <a class="reference external" href="../../auto_examples/linear_model/plot_ols_3d.html"><img alt="diabetes_ols_3" src="auto_examples/linear_model/images/sphx_glr_plot_ols_3d_003.png" /></a> <a class="reference external" href="../../auto_examples/linear_model/plot_ols_3d.html"><img alt="diabetes_ols_2" src="auto_examples/linear_model/images/sphx_glr_plot_ols_3d_002.png" /></a></strong></p><div class="admonition note">
<p class="admonition-title">Note</p>
<p>A representation of the full diabetes dataset would involve 11
dimensions (10 feature dimensions and one of the target variable). It
is hard to develop an intuition on such representation, but it may be
useful to keep in mind that it would be a fairly <em>empty</em> space.</p>
</div>
<p>We can see that, although feature 2 has a strong coefficient on the full
model, it conveys little information on <code class="docutils literal notranslate"><span class="pre">y</span></code> when considered with feature 1.</p>
<p>To improve the conditioning of the problem (i.e. mitigating the
<a class="reference internal" href="#curse-of-dimensionality"><span class="std std-ref">The curse of dimensionality</span></a>), it would be interesting to select only the
informative features and set non-informative ones, like feature 2 to 0. Ridge
regression will decrease their contribution, but not set them to zero. Another
penalization approach, called <a class="reference internal" href="../../modules/linear_model.html#lasso"><span class="std std-ref">Lasso</span></a> (least absolute shrinkage and
selection operator), can set some coefficients to zero. Such methods are
called <strong>sparse method</strong> and sparsity can be seen as an
application of Occam’s razor: <em>prefer simpler models</em>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">regr</span> <span class="o">=</span> <span class="n">linear_model</span><span class="o">.</span><span class="n">Lasso</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">scores</span> <span class="o">=</span> <span class="p">[</span><span class="n">regr</span><span class="o">.</span><span class="n">set_params</span><span class="p">(</span><span class="n">alpha</span><span class="o">=</span><span class="n">alpha</span><span class="p">)</span>
<span class="gp">... </span>              <span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">diabetes_X_train</span><span class="p">,</span> <span class="n">diabetes_y_train</span><span class="p">)</span>
<span class="gp">... </span>              <span class="o">.</span><span class="n">score</span><span class="p">(</span><span class="n">diabetes_X_test</span><span class="p">,</span> <span class="n">diabetes_y_test</span><span class="p">)</span>
<span class="gp">... </span>          <span class="k">for</span> <span class="n">alpha</span> <span class="ow">in</span> <span class="n">alphas</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">best_alpha</span> <span class="o">=</span> <span class="n">alphas</span><span class="p">[</span><span class="n">scores</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="nb">max</span><span class="p">(</span><span class="n">scores</span><span class="p">))]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">regr</span><span class="o">.</span><span class="n">alpha</span> <span class="o">=</span> <span class="n">best_alpha</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">regr</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">diabetes_X_train</span><span class="p">,</span> <span class="n">diabetes_y_train</span><span class="p">)</span>
<span class="go">Lasso(alpha=0.025118864315095794)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">regr</span><span class="o">.</span><span class="n">coef_</span><span class="p">)</span>
<span class="go">[   0.         -212.43764548  517.19478111  313.77959962 -160.8303982    -0.</span>
<span class="go"> -187.19554705   69.38229038  508.66011217   71.84239008]</span>
</pre></div>
</div>
<div class="topic">
<p class="topic-title"><strong>Different algorithms for the same problem</strong></p>
<p>Different algorithms can be used to solve the same mathematical
problem. For instance the <code class="docutils literal notranslate"><span class="pre">Lasso</span></code> object in scikit-learn
solves the lasso regression problem using a
<a class="reference external" href="https://en.wikipedia.org/wiki/Coordinate_descent">coordinate descent</a> method,
that is efficient on large datasets. However, scikit-learn also
provides the <a class="reference internal" href="../../modules/generated/sklearn.linear_model.LassoLars.html#sklearn.linear_model.LassoLars" title="sklearn.linear_model.LassoLars"><code class="xref py py-class docutils literal notranslate"><span class="pre">LassoLars</span></code></a> object using the <em>LARS</em> algorithm,
which is very efficient for problems in which the weight vector estimated
is very sparse (i.e. problems with very few observations).</p>
</div>
</div>
<div class="section" id="classification">
<span id="clf-tut"></span><h3>Classification<a class="headerlink" href="#classification" title="Permalink to this headline">¶</a></h3>
<a class="reference external image-reference" href="../../auto_examples/linear_model/plot_logistic.html"><img alt="auto_examples/linear_model/images/sphx_glr_plot_logistic_001.png" class="align-right" src="auto_examples/linear_model/images/sphx_glr_plot_logistic_001.png" /></a>
<p>For classification, as in the labeling
<a class="reference external" href="https://en.wikipedia.org/wiki/Iris_flower_data_set">iris</a> task, linear
regression is not the right approach as it will give too much weight to
data far from the decision frontier. A linear approach is to fit a sigmoid
function or <strong>logistic</strong> function:</p>
<div class="math notranslate nohighlight">
\[y = \textrm{sigmoid}(X\beta - \textrm{offset}) + \epsilon =
\frac{1}{1 + \textrm{exp}(- X\beta + \textrm{offset})} + \epsilon\]</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">log</span> <span class="o">=</span> <span class="n">linear_model</span><span class="o">.</span><span class="n">LogisticRegression</span><span class="p">(</span><span class="n">C</span><span class="o">=</span><span class="mf">1e5</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">log</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">iris_X_train</span><span class="p">,</span> <span class="n">iris_y_train</span><span class="p">)</span>
<span class="go">LogisticRegression(C=100000.0)</span>
</pre></div>
</div>
<p>This is known as <a class="reference internal" href="../../modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression" title="sklearn.linear_model.LogisticRegression"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogisticRegression</span></code></a>.</p>
<a class="reference external image-reference" href="../../auto_examples/linear_model/plot_iris_logistic.html"><img alt="auto_examples/linear_model/images/sphx_glr_plot_iris_logistic_001.png" src="auto_examples/linear_model/images/sphx_glr_plot_iris_logistic_001.png" /></a>
<div class="topic">
<p class="topic-title">Multiclass classification</p>
<p>If you have several classes to predict, an option often used is to fit
one-versus-all classifiers and then use a voting heuristic for the final
decision.</p>
</div>
<div class="topic">
<p class="topic-title">Shrinkage and sparsity with logistic regression</p>
<p>The <code class="docutils literal notranslate"><span class="pre">C</span></code> parameter controls the amount of regularization in the
<a class="reference internal" href="../../modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression" title="sklearn.linear_model.LogisticRegression"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogisticRegression</span></code></a> object: a large value for <code class="docutils literal notranslate"><span class="pre">C</span></code> results in
less regularization.
<code class="docutils literal notranslate"><span class="pre">penalty=&quot;l2&quot;</span></code> gives <a class="reference internal" href="#shrinkage"><span class="std std-ref">Shrinkage</span></a> (i.e. non-sparse coefficients), while
<code class="docutils literal notranslate"><span class="pre">penalty=&quot;l1&quot;</span></code> gives <a class="reference internal" href="#sparsity"><span class="std std-ref">Sparsity</span></a>.</p>
</div>
<div class="green topic">
<p class="topic-title"><strong>Exercise</strong></p>
<p>Try classifying the digits dataset with nearest neighbors and a linear
model. Leave out the last 10% and test prediction performance on these
observations.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">sklearn</span> <span class="kn">import</span> <span class="n">datasets</span><span class="p">,</span> <span class="n">neighbors</span><span class="p">,</span> <span class="n">linear_model</span>

<span class="n">X_digits</span><span class="p">,</span> <span class="n">y_digits</span> <span class="o">=</span> <span class="n">datasets</span><span class="o">.</span><span class="n">load_digits</span><span class="p">(</span><span class="n">return_X_y</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="n">X_digits</span> <span class="o">=</span> <span class="n">X_digits</span> <span class="o">/</span> <span class="n">X_digits</span><span class="o">.</span><span class="n">max</span><span class="p">()</span>

</pre></div>
</div>
<p>Solution: <a class="reference download internal" download="" href="../../_downloads/3471d630d42778e8ec2683f7424fa2cb/plot_digits_classification_exercise.py"><code class="xref download docutils literal notranslate"><span class="pre">../../auto_examples/exercises/plot_digits_classification_exercise.py</span></code></a></p>
</div>
</div>
</div>
<div class="section" id="support-vector-machines-svms">
<h2>Support vector machines (SVMs)<a class="headerlink" href="#support-vector-machines-svms" title="Permalink to this headline">¶</a></h2>
<div class="section" id="linear-svms">
<h3>Linear SVMs<a class="headerlink" href="#linear-svms" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="../../modules/svm.html#svm"><span class="std std-ref">Support Vector Machines</span></a> belong to the discriminant model family: they try to find a combination of
samples to build a plane maximizing the margin between the two classes.
Regularization is set by the <code class="docutils literal notranslate"><span class="pre">C</span></code> parameter: a small value for <code class="docutils literal notranslate"><span class="pre">C</span></code> means the margin
is calculated using many or all of the observations around the separating line
(more regularization);
a large value for <code class="docutils literal notranslate"><span class="pre">C</span></code> means the margin is calculated on observations close to
the separating line (less regularization).</p>
<table class="centered docutils align-default">
<colgroup>
<col style="width: 49%" />
<col style="width: 51%" />
</colgroup>
<thead>
<tr class="row-odd"><th class="head"><p><strong>Unregularized SVM</strong></p></th>
<th class="head"><p><strong>Regularized SVM (default)</strong></p></th>
</tr>
</thead>
<tbody>
<tr class="row-even"><td><p><a class="reference external" href="../../auto_examples/svm/plot_svm_margin.html"><img alt="svm_margin_unreg" src="auto_examples/svm/images/sphx_glr_plot_svm_margin_001.png" /></a></p></td>
<td><p><a class="reference external" href="../../auto_examples/svm/plot_svm_margin.html"><img alt="svm_margin_reg" src="auto_examples/svm/images/sphx_glr_plot_svm_margin_002.png" /></a></p></td>
</tr>
</tbody>
</table>
<div class="topic">
<p class="topic-title">Example:</p>
<ul class="simple">
<li><p><a class="reference internal" href="../../auto_examples/svm/plot_iris_svc.html#sphx-glr-auto-examples-svm-plot-iris-svc-py"><span class="std std-ref">Plot different SVM classifiers in the iris dataset</span></a></p></li>
</ul>
</div>
<p>SVMs can be used in regression –<a class="reference internal" href="../../modules/generated/sklearn.svm.SVR.html#sklearn.svm.SVR" title="sklearn.svm.SVR"><code class="xref py py-class docutils literal notranslate"><span class="pre">SVR</span></code></a> (Support Vector Regression)–, or in
classification –<a class="reference internal" href="../../modules/generated/sklearn.svm.SVC.html#sklearn.svm.SVC" title="sklearn.svm.SVC"><code class="xref py py-class docutils literal notranslate"><span class="pre">SVC</span></code></a> (Support Vector Classification).</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">sklearn</span> <span class="kn">import</span> <span class="n">svm</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">svc</span> <span class="o">=</span> <span class="n">svm</span><span class="o">.</span><span class="n">SVC</span><span class="p">(</span><span class="n">kernel</span><span class="o">=</span><span class="s1">&#39;linear&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">svc</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">iris_X_train</span><span class="p">,</span> <span class="n">iris_y_train</span><span class="p">)</span>
<span class="go">SVC(kernel=&#39;linear&#39;)</span>
</pre></div>
</div>
<div class="admonition warning">
<p class="admonition-title">Warning</p>
<p><strong>Normalizing data</strong></p>
<p>For many estimators, including the SVMs, having datasets with unit
standard deviation for each feature is important to get good
prediction.</p>
</div>
</div>
<div class="section" id="using-kernels">
<span id="using-kernels-tut"></span><h3>Using kernels<a class="headerlink" href="#using-kernels" title="Permalink to this headline">¶</a></h3>
<p>Classes are not always linearly separable in feature space. The solution is to
build a decision function that is not linear but may be polynomial instead.
This is done using the <em>kernel trick</em> that can be seen as
creating a decision energy by positioning <em>kernels</em> on observations:</p>
<table class="centered docutils align-default">
<colgroup>
<col style="width: 50%" />
<col style="width: 50%" />
</colgroup>
<tbody>
<tr class="row-odd"><td><p><strong>Linear kernel</strong></p></td>
<td><p><strong>Polynomial kernel</strong></p></td>
</tr>
<tr class="row-even"><td><p><a class="reference external" href="../../auto_examples/svm/plot_svm_kernels.html"><img alt="svm_kernel_linear" src="auto_examples/svm/images/sphx_glr_plot_svm_kernels_001.png" /></a></p></td>
<td><p><a class="reference external" href="../../auto_examples/svm/plot_svm_kernels.html"><img alt="svm_kernel_poly" src="auto_examples/svm/images/sphx_glr_plot_svm_kernels_002.png" /></a></p></td>
</tr>
<tr class="row-odd"><td><div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">svc</span> <span class="o">=</span> <span class="n">svm</span><span class="o">.</span><span class="n">SVC</span><span class="p">(</span><span class="n">kernel</span><span class="o">=</span><span class="s1">&#39;linear&#39;</span><span class="p">)</span>
</pre></div>
</div>
</td>
<td><div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">svc</span> <span class="o">=</span> <span class="n">svm</span><span class="o">.</span><span class="n">SVC</span><span class="p">(</span><span class="n">kernel</span><span class="o">=</span><span class="s1">&#39;poly&#39;</span><span class="p">,</span>
<span class="gp">... </span>              <span class="n">degree</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># degree: polynomial degree</span>
</pre></div>
</div>
</td>
</tr>
</tbody>
</table>
<table class="centered docutils align-default">
<colgroup>
<col style="width: 100%" />
</colgroup>
<tbody>
<tr class="row-odd"><td><p><strong>RBF kernel (Radial Basis Function)</strong></p></td>
</tr>
<tr class="row-even"><td><p><a class="reference external" href="../../auto_examples/svm/plot_svm_kernels.html"><img alt="svm_kernel_rbf" src="auto_examples/svm/images/sphx_glr_plot_svm_kernels_003.png" /></a></p></td>
</tr>
<tr class="row-odd"><td><div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">svc</span> <span class="o">=</span> <span class="n">svm</span><span class="o">.</span><span class="n">SVC</span><span class="p">(</span><span class="n">kernel</span><span class="o">=</span><span class="s1">&#39;rbf&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># gamma: inverse of size of</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># radial kernel</span>
</pre></div>
</div>
</td>
</tr>
</tbody>
</table>
<div class="topic">
<p class="topic-title"><strong>Interactive example</strong></p>
<p>See the <a class="reference internal" href="../../auto_examples/applications/svm_gui.html#sphx-glr-auto-examples-applications-svm-gui-py"><span class="std std-ref">SVM GUI</span></a> to download
<code class="docutils literal notranslate"><span class="pre">svm_gui.py</span></code>; add data points of both classes with right and left button,
fit the model and change parameters and data.</p>
</div>
<a class="reference external image-reference" href="../../auto_examples/datasets/plot_iris_dataset.html"><img alt="auto_examples/datasets/images/sphx_glr_plot_iris_dataset_001.png" class="align-right" src="auto_examples/datasets/images/sphx_glr_plot_iris_dataset_001.png" /></a>
<div class="green topic">
<p class="topic-title"><strong>Exercise</strong></p>
<p>Try classifying classes 1 and 2 from the iris dataset with SVMs, with
the 2 first features. Leave out 10% of each class and test prediction
performance on these observations.</p>
<p><strong>Warning</strong>: the classes are ordered, do not leave out the last 10%,
you would be testing on only one class.</p>
<p><strong>Hint</strong>: You can use the <code class="docutils literal notranslate"><span class="pre">decision_function</span></code> method on a grid to get
intuitions.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">iris</span> <span class="o">=</span> <span class="n">datasets</span><span class="o">.</span><span class="n">load_iris</span><span class="p">()</span>
<span class="n">X</span> <span class="o">=</span> <span class="n">iris</span><span class="o">.</span><span class="n">data</span>
<span class="n">y</span> <span class="o">=</span> <span class="n">iris</span><span class="o">.</span><span class="n">target</span>

<span class="n">X</span> <span class="o">=</span> <span class="n">X</span><span class="p">[</span><span class="n">y</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">,</span> <span class="p">:</span><span class="mi">2</span><span class="p">]</span>
<span class="n">y</span> <span class="o">=</span> <span class="n">y</span><span class="p">[</span><span class="n">y</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">]</span>
</pre></div>
</div>
<p>Solution: <a class="reference download internal" download="" href="../../_downloads/ee0ec20765dc877f0c987ff30d473cd4/plot_iris_exercise.py"><code class="xref download docutils literal notranslate"><span class="pre">../../auto_examples/exercises/plot_iris_exercise.py</span></code></a></p>
</div>
</div>
</div>
</div>


      </div>
    <div class="container">
      <footer class="sk-content-footer">
            &copy; 2007 - 2019, scikit-learn developers (BSD License).
          <a href="../../_sources/tutorial/statistical_inference/supervised_learning.rst.txt" rel="nofollow">Show this page source</a>
      </footer>
    </div>
  </div>
</div>
<script src="../../_static/js/vendor/bootstrap.min.js"></script>

<script>
    window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
    ga('create', 'UA-22606712-2', 'auto');
    ga('set', 'anonymizeIp', true);
    ga('send', 'pageview');
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>


<script>
$(document).ready(function() {
    /* Add a [>>>] button on the top-right corner of code samples to hide
     * the >>> and ... prompts and the output and thus make the code
     * copyable. */
    var div = $('.highlight-python .highlight,' +
                '.highlight-python3 .highlight,' +
                '.highlight-pycon .highlight,' +
		'.highlight-default .highlight')
    var pre = div.find('pre');

    // get the styles from the current theme
    pre.parent().parent().css('position', 'relative');
    var hide_text = 'Hide prompts and outputs';
    var show_text = 'Show prompts and outputs';

    // create and add the button to all the code blocks that contain >>>
    div.each(function(index) {
        var jthis = $(this);
        if (jthis.find('.gp').length > 0) {
            var button = $('<span class="copybutton">&gt;&gt;&gt;</span>');
            button.attr('title', hide_text);
            button.data('hidden', 'false');
            jthis.prepend(button);
        }
        // tracebacks (.gt) contain bare text elements that need to be
        // wrapped in a span to work with .nextUntil() (see later)
        jthis.find('pre:has(.gt)').contents().filter(function() {
            return ((this.nodeType == 3) && (this.data.trim().length > 0));
        }).wrap('<span>');
    });

    // define the behavior of the button when it's clicked
    $('.copybutton').click(function(e){
        e.preventDefault();
        var button = $(this);
        if (button.data('hidden') === 'false') {
            // hide the code output
            button.parent().find('.go, .gp, .gt').hide();
            button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'hidden');
            button.css('text-decoration', 'line-through');
            button.attr('title', show_text);
            button.data('hidden', 'true');
        } else {
            // show the code output
            button.parent().find('.go, .gp, .gt').show();
            button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'visible');
            button.css('text-decoration', 'none');
            button.attr('title', hide_text);
            button.data('hidden', 'false');
        }
    });

	/*** Add permalink buttons next to glossary terms ***/
	$('dl.glossary > dt[id]').append(function() {
		return ('<a class="headerlink" href="#' +
			    this.getAttribute('id') +
			    '" title="Permalink to this term">¶</a>');
	});
  /*** Hide navbar when scrolling down ***/
  // Returns true when headerlink target matches hash in url
  (function() {
    hashTargetOnTop = function() {
        var hash = window.location.hash;
        if ( hash.length < 2 ) { return false; }

        var target = document.getElementById( hash.slice(1) );
        if ( target === null ) { return false; }

        var top = target.getBoundingClientRect().top;
        return (top < 2) && (top > -2);
    };

    // Hide navbar on load if hash target is on top
    var navBar = document.getElementById("navbar");
    var navBarToggler = document.getElementById("sk-navbar-toggler");
    var navBarHeightHidden = "-" + navBar.getBoundingClientRect().height + "px";
    var $window = $(window);

    hideNavBar = function() {
        navBar.style.top = navBarHeightHidden;
    };

    showNavBar = function() {
        navBar.style.top = "0";
    }

    if (hashTargetOnTop()) {
        hideNavBar()
    }

    var prevScrollpos = window.pageYOffset;
    hideOnScroll = function(lastScrollTop) {
        if (($window.width() < 768) && (navBarToggler.getAttribute("aria-expanded") === 'true')) {
            return;
        }
        if (lastScrollTop > 2 && (prevScrollpos <= lastScrollTop) || hashTargetOnTop()){
            hideNavBar()
        } else {
            showNavBar()
        }
        prevScrollpos = lastScrollTop;
    };

    /*** high preformance scroll event listener***/
    var raf = window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        window.oRequestAnimationFrame;
    var lastScrollTop = $window.scrollTop();

    if (raf) {
        loop();
    }

    function loop() {
        var scrollTop = $window.scrollTop();
        if (lastScrollTop === scrollTop) {
            raf(loop);
            return;
        } else {
            lastScrollTop = scrollTop;
            hideOnScroll(lastScrollTop);
            raf(loop);
        }
    }
  })();
});

</script>
    
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js"></script>
    
</body>
</html>